package com.moshang.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moshang.blog.core.constant.CurrentUser;
import com.moshang.blog.core.constant.MySysUser;
import com.moshang.blog.core.utils.PageUtil;
import com.moshang.blog.core.utils.RestResponse;
import com.moshang.blog.entity.SysUserRole;
import com.moshang.blog.entity.activity.LeaveOpinion;
import com.moshang.blog.model.BaseTask;
import com.moshang.blog.model.UserLeave;
import com.moshang.blog.service.SysUserRoleService;
import com.moshang.blog.service.UserLeaveService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author xww
 * @Description //TODO
 * @Date 2019/7/11   9:44
 **/
@Controller
@RequestMapping("/task")
public class TaskController {

    private final  String prefix="act/task/";
    private final String leaveOpinionList = "leaveOpinionList";
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private UserLeaveService userLeaveService;
    @Autowired
    private RuntimeService runtimeService;


    /**
     * ---------我的任务---------
     */
    @GetMapping(value = "showTask")
    public String showTask() {
        return prefix+"taskList";
    }

    @GetMapping(value = "showTaskList")
    @ResponseBody
    public PageUtil<com.moshang.blog.model.Task> showTaskList(Integer page, Integer limit) {
        PageUtil<com.moshang.blog.model.Task>pageUtil=new PageUtil<>();
        CurrentUser user = MySysUser.currentUser();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(user.getId());
        QueryWrapper<SysUserRole> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        List<SysUserRole> userRoles = sysUserRoleService.list(queryWrapper);
        List<String> roleString = new ArrayList<>();
        for (SysUserRole sru : userRoles) {
            roleString.add(sru.getRoleId().toString());
        }
        List<Task> taskList = taskService.createTaskQuery().taskCandidateUser(user.getId().toString()).list();
        List<Task> assigneeList = taskService.createTaskQuery().taskAssignee(user.getId().toString()).list();
        List<Task> candidateGroup = taskService.createTaskQuery().taskCandidateGroupIn(roleString).list();
        taskList.addAll(assigneeList);
        taskList.addAll(candidateGroup);
        List<com.moshang.blog.model.Task> tasks = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        com.moshang.blog.model.Task taskEntity = null;

        Map<String, Map<String, Object>> mapMap = new HashMap<>();
        Map<String, Object> objectMap = null;
        Set<String> taskSet = new HashSet<String>();
        for (Task task1 : taskList) {
            objectMap = new HashMap<>();
            String taskId = task1.getId();
            if (taskSet.contains(taskId)) {
                continue;
            }

            map = taskService.getVariables(taskId);
            BaseTask userLeave = (BaseTask) map.get("baseTask");

            taskEntity = new com.moshang.blog.model.Task(task1);
            taskEntity.setAssignee(user.getRealName());
            taskEntity.setUserName(userLeave.getUserName());
            taskEntity.setReason(userLeave.getReason());
            taskEntity.setUrlpath(userLeave.getUrlPath());
            /**如果是自己*/
            if (user.getId().equals(userLeave.getUserId())) {
                if (map.get("flag") != null) {
                    if (!(boolean) map.get("flag")) {
                        objectMap.put("flag", true);
                    } else {
                        objectMap.put("flag", false);
                    }
                } else {
                    objectMap.put("flag", true);
                }
            } else {
                objectMap.put("flag", false);
            }
            mapMap.put(taskEntity.getId(), objectMap);
            tasks.add(taskEntity);
            taskSet.add(taskId);
        }
        pageUtil.setCount(taskList.size());
        pageUtil.setData(tasks);
        pageUtil.setPage(page);
        Integer totalPage=(pageUtil.getCount()-1)/limit;
        pageUtil.setTotalPage(totalPage);
        return pageUtil;
    }

    /**
     * 进入办理页面
     * @param model
     * @param taskId
     * @return
     */
    @GetMapping("agent/{id}")
    public String agent(Model model, @PathVariable("id") String taskId) {
        Map<String, Object> variables = taskService.getVariables(taskId);
        BaseTask baseTask = (BaseTask) variables.get("baseTask");
        model.addAttribute("leaveUrl", baseTask.getUrlPath());
        model.addAttribute("taskId", taskId);
        return prefix+"/agent";
    }
    @PostMapping("agent/complete")
    @ResponseBody
    public RestResponse complete(LeaveOpinion op, HttpServletRequest request) {
        Map<String, Object> variables = taskService.getVariables(op.getTaskId());
        CurrentUser user = MySysUser.currentUser();
        op.setCreateTime(new Date());
        op.setOpId(user.getId().toString());
        op.setOpName(user.getRealName());
        RestResponse restResponse = new RestResponse();
        Map<String, Object> map = new HashMap<>();
        map.put("flag", op.isFlag());
        Task task = taskService.createTaskQuery()//
                .taskId(op.getTaskId())//使用任务ID查询
                .singleResult();
//获取流程实例ID
        String processInstanceId = task.getProcessInstanceId();
        //判断节点是否已经拒绝过一次了
        Object needend = variables.get("needend");
        if (needend != null && (boolean) needend && (!op.isFlag())) {
            map.put("needfinish", -1); //结束

        } else {
            if (op.isFlag()) {
                map.put("needfinish", 1);//通过下一个节点
            } else {
                map.put("needfinish", 0);//不通过
            }
        }
        //审批信息叠加
        List<LeaveOpinion> leaveList = new ArrayList<>();
        Object o = variables.get(leaveOpinionList);
        if (o != null) {
            leaveList = (List<LeaveOpinion>) o;
        }
        leaveList.add(op);
        map.put(leaveOpinionList, leaveList);
        taskService.complete(op.getTaskId(), map);

        restResponse.setMessage("审核成功" + (op.isFlag() ? "<font style='color:green'>[通过]</font>" : "<font style='color:red'>[未通过]</font>"));
        ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
                .processInstanceId(processInstanceId)//使用流程实例ID查询
                .singleResult();
        if (pi==null){
            //流程结束
            //更新审核信息表
            UserLeave userLeave=(UserLeave)variables.get("baseTask");
            if (op.isFlag()){
                userLeave.setStatus("审核通过");
            } else {
                userLeave.setStatus("审核不通过");
            }
            userLeave.setUpdateBy(user.getId().toString());
            userLeave.setUserName(user.getRealName());
            userLeave.setUpdateTime(new Date());
            userLeave.setProcessInstanceId(processInstanceId);
            userLeaveService.updateById(userLeave);
        }
        restResponse.setSuccess(true);
        return restResponse;
    }

}
